<?php

namespace App\Admin\Controllers;

use App\Admin\Forms\EntryAreaSetting;
use App\Admin\Forms\EntryInformation;
use App\Admin\Renderable\UserTable;
use App\Admin\Repositories\Activity;
use App\Models\ActivityAreaSetting;
use App\Models\ActivityInformation;
use App\Models\Category;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Log;
use zgldh\QiniuStorage\QiniuStorage;

class ActivityController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Activity(), function (Grid $grid) {
            $grid->disableViewButton();
            $grid->disableCreateButton();
            $grid->disableDeleteButton();
            $grid->disableRowSelector();
            $grid->column('id')->sortable();
            $grid->column('activity_name');
            // $grid->column('desc');
            $grid->column('cover')->image();
            // $grid->column('remarks');
            $grid->column('status')->switch();

            // $grid->column('赛区设置')->display('赛区设置')->link(admin_url('activity/area'));
            // $grid->column('赛区设置')->display('赛区设置')->link(function ($value) {
            //     return admin_url('activity/area?act_id=' . $this->id);
            // }, '');



            $grid->column('created_at');
            // $grid->column('updated_at')->sortable();
            $grid->model()->orderBy('id', 'desc');
            $grid->model()->where('is_del', 0);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('activity_name');
                $filter->scope('1', '已审核')->where('status', 1);
                $filter->scope('0', '未审核')->where('status', 0);
            });


            /**
             * 按钮控制.
             */
            // @permissions
            if (!Admin::user()->can('activity-medical-create')) {
                $grid->disableCreateButton();
                $grid->disableQuickCreateButton();
            }
            // @permissions
            if (!Admin::user()->can('activity-medical-update')) {
                $grid->disableEditButton();
                $grid->disableQuickEditButton();
            }
            // @permissions
            if (!Admin::user()->can('activity-medical-delete')) {
                $grid->disableDeleteButton();
            }
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Activity(), function (Show $show) {
            // @permissions
            if (!Admin::user()->can('activity-medical-delete')) {
                $show->disableDeleteButton();
            }

            // @permissions
            if (!Admin::user()->can('activity-medical-update') || (Admin::user()->id != $show->model()->admin_id) && !Admin::user()->isAdministrator()) {
                $show->disableEditButton();
            }

            $show->field('id');
            $show->field('activity_name');
            $show->field('desc')->unescape();
            $show->field('cover')->image();
            $show->field('remarks')->unescape();
            $show->status()->using(['1' => '显示', '0' => '不显示']);
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Activity('activityInfo'), function (Form $form) {
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableCreatingCheck();
            // @permissions
            if (!Admin::user()->can('activity-medical-delete')) {
                $form->disableDeleteButton();
            }
            $form->display('id');
            $form->text('activity_name');
            $form->multipleSelect('category_ids', '科室分类')->options(Category::where('parent_id', 1)->where('status', 1)->pluck('title', 'id'))->saving(function ($value) {
                $category_ids = implode(',', $value);
                return $category_ids;
            })->label();
            $form->textarea('desc');
            $form->image('cover')->autoUpload()->move('medical/activity/image/' . date('Y/m'));;
            $form->editor('remarks')->languageUrl(admin_asset('@admin/dcat/plugins/tinymce/langs/zh_CN.js'));
            $form->hidden('status')
                // ->customFormat(function ($v) {
                //     return $v == 1 ? 1 : 0;
                // })
                ->saving(function ($v) {
                    return $v;
                });

            $filename = md5(uniqid()) . '.mp4';
            $disk = QiniuStorage::disk('qiniu');
            // 回调信息, Dcat 上传文件需要的报文格式
            $callBack = [
                'status' => true,
                'data'   => [
                    'id'   => $filename,
                    'name' => $filename,
                    'path' => $filename,
                    'url'  => env('QINIU_DOMAINS') . '/' . $filename,
                ],
            ];
            $policy   = [
                'returnBody' => json_encode($callBack),
            ];
            // 七牛云上传 token
            $token    = $disk->uploadToken($filename, 3600, $policy);

            $form->image('activityInfo.cover', '视频封面图')->autoUpload()->move('medical/yangzijiang/cover/' . date('Y/m'));

            $form->file('activityInfo.video', '宣传视频')
                ->disk('qiniu')
                ->autoUpload()
                ->accept('mp4')
                // 提示文字
                ->help('仅支持MP4格式')
                // ->move('medical/innovent/video/' . date('Y/m'))
                ->maxSize(1024 * 1024)
                // 关闭页面删除
                ->removable(false)
                // ->chunked()
                // ->chunkSize(1024 * 3)
                // ->threads(8) // 设置上传地址
                ->url('https://up-z1.qiniup.com')
                // 自定义 webuploader 配置
                // Dcat 默认 name 为 _file_
                ->options(['fileVal' => 'file'])
                // 上传事件
                ->on(
                    'startUpload',
                    <<<JS
        function () {
            console.log('文件开始上传...', this);
            // 上传文件前附加自定义参数到文件上传接口
            this.uploader.options.formData['token'] = "$token";
            this.uploader.options.formData['fileName'] = "$filename";
            this.uploader.options.formData['key'] = "$filename";
        }
JS
                );
            $form->textarea('activityInfo.activity_theme', '活动主旨');
            $form->file('activityInfo.medical_template', '病例模板')->autoUpload()->move('medical/yangzijiang/medical_template/' . date('Y/m'));
            $form->image('activityInfo.entry_process_pc', '参赛流程PC端')->autoUpload()->move('medical/yangzijiang/entry_process_pc/' . date('Y/m'));
            $form->image('activityInfo.entry_process_mobile', '参赛流程移动端')->autoUpload()->move('medical/yangzijiang/entry_process_mobile/' . date('Y/m'));
            $form->editor('activityInfo.entry_information', '参赛信息');
            $form->radio('status', '状态')->options([0 => '未审核', 1 => '已审核'])->default(1);

            // $form->array('expert_judge', '专家评委', function ($table) {
            //     $table->image('avatar', '头像')->autoUpload()->move('medical/innovent/avatar/' . date('Y/m'))->options(['disableGlobalDnd' => true])->saveFullUrl();
            //     $table->text('name', '专家名称');
            //     // $table->textarea('desc');
            // })->saveAsJson();

            // $form->ignore(['expert_judge']);
            // $result 是添加成功后的主键id 修改是表示成功的 1
            $form->saved(function (Form $form, $result) {
                $data = $form->updates();

                Log::info('====== 活动信息 ======' . json_encode($data));

                // if ($form->isCreating()) {
                //     ActivityAreaSetting::create(
                //         [
                //             'act_id' => $result,
                //             'title' => $data['activity_name'],
                //             'parent_id' => 0,
                //         ]
                //     );
                //     if (isset($data['expert_judge'])) {
                //         ActivityInformation::updateOrCreate(['act_id' => $result], ['expert_judge' => $data['expert_judge']]);
                //     }
                // }

                // if ($form->isEditing() && (isset($data['activity_name']) && $data['activity_name'] != '')) {
                //     $areaModel = ActivityAreaSetting::where('act_id', $form->model()->id)->where('parent_id', 0)->first();
                //     $areaModel->title = $data['activity_name'];
                //     $areaModel->save();
                //     if (isset($data['expert_judge'])) {
                //         ActivityInformation::updateOrCreate(['act_id' => $form->model()->id], ['expert_judge' => $data['expert_judge']]);
                //     }
                // }
            });
            // $form->display('created_at');
            // $form->display('updated_at');
        });
    }
}
